package com.ycc.service.impl;


import com.alibaba.fastjson.JSON;
import com.ycc.mapper.MyMapper;
import com.ycc.pojo.Content;
import com.ycc.service.ContentService;
import org.apache.ibatis.annotations.Mapper;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.FuzzyQueryBuilder;
import org.elasticsearch.index.query.MatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

//业务编写
@Service
public class ContentServiceImpl implements ContentService {
    @Autowired
    private RestHighLevelClient restHighLevelClient;
    @Autowired
    private MyMapper mapper;


    //1、解析数据放到es索引中
    @Override
    public Boolean parseContent(String keywords) throws Exception {

        List<Content> contents = mapper.selectAll();
        //查询出来的数据，放ES进去
        BulkRequest bulkRequest = new BulkRequest();
        bulkRequest.timeout("2m");

        for (int i=0;i<contents.size();i++){
            bulkRequest.add(
                    new IndexRequest("shopping_cart")
                    .source(JSON.toJSONString(contents.get(i)), XContentType.JSON));
        }
        BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
        return !bulk.hasFailures();
    }


    //2、从es中拿出来，并分页
    @Override
    public List<Map<String,Object>> searchPage(String keyword,int pageNo,int pageSize) throws Exception {
        if (pageNo<=1){
            pageNo=1;
        }

        //条件搜索
        SearchRequest searchRequest = new SearchRequest("shopping_cart");
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();

        //分页
        sourceBuilder.from(pageNo);
        sourceBuilder.size(pageSize);


        //精准匹配
        TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("title", keyword);
        sourceBuilder.query(termQueryBuilder);
        sourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));

        //执行搜索
        searchRequest.source(sourceBuilder);
        SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
        //解析结果
        ArrayList<Map<String,Object>> list = new ArrayList<>();
        for (SearchHit documentFields : searchResponse.getHits().getHits()){
            list.add(documentFields.getSourceAsMap());
        }
        return list;
    }


    //3、从es中拿出来，高亮并分页
    @Override
    public List<Map<String,Object>> searchPageHighlight(String keyword,int pageNo,int pageSize) throws Exception {
        if (pageNo<=1){
            pageNo=0;
        }

        //条件搜索
        SearchRequest searchRequest = new SearchRequest("shopping_cart");
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();

        //分页
        sourceBuilder.from(pageNo);
        sourceBuilder.size(pageSize);


        //精准匹配
        TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("title", keyword);
        sourceBuilder.query(termQueryBuilder);
//        MatchQueryBuilder matchQueryBuilder = QueryBuilders.matchQuery("title", keyword);
//        sourceBuilder.query(matchQueryBuilder);
//        FuzzyQueryBuilder fuzzyQueryBuilder = QueryBuilders.fuzzyQuery("title", keyword);
//        sourceBuilder.query(fuzzyQueryBuilder);
        sourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));


        //高亮
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field("title");
        highlightBuilder.requireFieldMatch(false);//多个高亮显示关闭
        highlightBuilder.preTags("<span style='color:red'>");
        highlightBuilder.postTags("</span>");
        sourceBuilder.highlighter(highlightBuilder);


        //执行搜索
        searchRequest.source(sourceBuilder);
        SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
        //解析结果
        ArrayList<Map<String,Object>> list = new ArrayList<>();
        for (SearchHit hit : searchResponse.getHits().getHits()){
            //解析高亮的字段
            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
            HighlightField title = highlightFields.get("title");
            Map<String, Object> sourceAsMap = hit.getSourceAsMap();
            if (title!=null){
                Text[] fragments = title.fragments();
                String name = "";
                for (Text text : fragments) {
                    name +=text;
                }
                sourceAsMap.put("title",name);//高亮字段替换原来的内容
            }
            list.add(hit.getSourceAsMap());
        }
        list.forEach(System.out::println);
        return list;
    }

    @Override
    public Object selectByTitle(String title) {
        return mapper.selectByTitle(title);
    }

    @Override
    public Content selectById(String id){
        return mapper.selectById(id);
    }

    @Override
    public List<Map<String, Object>> searchAllPageHighlight() throws IOException {
        //条件搜索
        SearchRequest searchRequest = new SearchRequest("shopping_cart");
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();



        TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("title","java");
        sourceBuilder.query(termQueryBuilder);
        sourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));

        //高亮
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field("title");
        highlightBuilder.requireFieldMatch(false);//多个高亮显示关闭
        highlightBuilder.preTags("<span style='color:red'>");
        highlightBuilder.postTags("</span>");
        sourceBuilder.highlighter(highlightBuilder);


        //执行搜索
        searchRequest.source(sourceBuilder);
        SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
        //解析结果
        ArrayList<Map<String,Object>> list = new ArrayList<>();
        for (SearchHit hit : searchResponse.getHits().getHits()){
            //解析高亮的字段
            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
            HighlightField title = highlightFields.get("title");
            Map<String, Object> sourceAsMap = hit.getSourceAsMap();
            if (title!=null){
                Text[] fragments = title.fragments();
                String name = "";
                for (Text text : fragments) {
                    name +=text;
                }
                sourceAsMap.put("title",name);//高亮字段替换原来的内容
            }
            list.add(hit.getSourceAsMap());
        }
        list.forEach(System.out::println);
        return list;
    }

}





















